import 'package:boss/main.dart';
import 'package:boss/models/role.dart';
import 'package:flutter/material.dart';
import 'package:async/async.dart';

class RoleDetailProvider extends ChangeNotifier {
  Role role;

  List<Permissions> perms;
  List<String> tabs;
  int tabPosition = 0;

  List<Permissions> get contentPerms => perms[tabPosition].userPermission;

  setRole(Role role) {
    this.role = Role.fromJson(role?.toJson() ?? {});
    perms = null;
    tabs = null;
    tabPosition = 0;
  }

  Future<Result<List<Permissions>>> queryPerms() async {
    final res = await api.queryRulePermissions(role?.roleId ?? 0);
    if (!res.successful()) {
      return Result.error(res.msg);
    }
    perms = res.data ?? [];

    tabs = perms.map((e) => e.menuName).toList();

    return Result.value(res.data);
  }

  togglePerms(bool selectedAll) {
    contentPerms?.forEach((element) {
      element.permissionSelect = selectedAll;
    });
    notifyListeners();
  }

  togglePerm(int index) {
    contentPerms[index].permissionSelect = !contentPerms[index].permissionSelect;
    notifyListeners();
  }

  setTabPosition(int position) {
    tabPosition = position;
    notifyListeners();
  }
}
